package com.hulk.dryad.web.shedlock;


import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.hulk.dryad.manage.framework.datasource.DynamicDataSourceHolder;
import com.hulk.dryad.persistence.entity.GenDatasourceConfModel;
import com.hulk.dryad.persistence.entity.enums.DsConfTypeEnum;
import com.hulk.dryad.persistence.entity.enums.DsJdbcUrlEnum;
import com.hulk.dryad.manage.provider.service.GenDatasourceConfService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 动态添加数据源到内存
 * @Author: hulk
 * @E-mail: 29572320@qq.com
 * @Date: Create in 2019-05-18 22:37
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DruidDataSourceScheduler {

	@Value("${spring.datasource.dynamic.primary:DB_0}")
	private String primary;
	private final GenDatasourceConfService datasourceConfService;
	private final DynamicRoutingDataSource dynamicRoutingDataSource;


	@Scheduled(cron = "0 */3 * * * ?")
	public void druidDataSourceAdd() {
		try {
			DynamicDataSourceHolder.set(primary);
			List<GenDatasourceConfModel> dsList = datasourceConfService.list();
			if (dsList == null || dsList.isEmpty()) {
				log.info("项目启动时动态添加数据源为0个");
				return;
			}
			for (GenDatasourceConfModel model : dsList) {
				Integer confType = model.getConfType();
				String dsType = model.getDsType();
				String name = model.getName();
				Set<String> poolNames = dynamicRoutingDataSource.getCurrentDataSources().entrySet().stream().map((entry)->entry.getKey()).collect(Collectors.toSet());
				if(poolNames.contains(name)){
					continue;
				}
				String url;
				// JDBC 配置形式
				DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(dsType);
				if (DsConfTypeEnum.JDBC.getType().equals(confType)) {
					url = model.getUrl();
				} else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(dsType)) {
					String host = model.getHost();
					Integer port = model.getPort();
					String dsName = model.getDsName();
					String instance = model.getInstance();
					url = String.format(urlEnum.getUrl(), host, instance, port, dsName);
				} else {
					String host = model.getHost();
					Integer port = model.getPort();
					String dsName = model.getDsName();
					url = String.format(urlEnum.getUrl(), host, port, dsName);
				}

				model.setUrl(url);
				// 添加动态数据源
				datasourceConfService.addDynamicDataSource(model);
				log.info("项目启动时动态添加数据源信息:[{}]", model);
			}
			log.info("项目启动时动态添加数据源为[{}]个", dsList.size());
		} catch (Exception e) {
			e.printStackTrace();
			log.error("",e);
		} finally {
			DynamicDataSourceContextHolder.clear();
		}

	}

}